package utils;

import java.util.ArrayList;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;

import model.Delivery;

public class BookOfDelivery{
	
	private static BookOfDelivery instance;
	
	private BookOfDelivery(){}
	
	public static BookOfDelivery getInstance(){
		if(instance == null){
			instance = new BookOfDelivery();
		}
		return instance;
	}
	
	public void insertDelivery(Delivery d){
		Document dom = Dom.getXMLFile("bookOfDelivery.xml");
		Element root = dom.getRootElement();
		int bookSize = root.getChildren().size();
		
			Element delivery = new Element("delivery"+(bookSize+1));
			
				Element restaurant = new Element("restaurant");
				restaurant.setText(d.getRestaurantName());
				delivery.addContent(restaurant);
				
				Element confirmNum = new Element("confirmnum");
				confirmNum.setText(d.getDeliveryConfirmNumber());
				delivery.addContent(confirmNum);
				
				String[] infos = {"Civic address", "City", "Postal code", "Province", "Country", "Date", "Time"};
				for(int i = 0; i < infos.length; i++){
					Element info = new Element(infos[i].replace(" ", "").toLowerCase());
					info.setText(d.getDeliveryInfo(infos[i]));
					delivery.addContent(info);
				}
				
				Element command = new Element("command");
					
					ArrayList<Dish> dishes = d.getDeliveryElements();
					Iterator<Dish> dishesIt = dishes.iterator();
					while(dishesIt.hasNext()){
						Dish dish = dishesIt.next();
						Element dishElement = new Element("dish"+(dishes.indexOf(dish)+1));
						
							Element dishName = new Element("name");
							dishName.setText(dish.getName());
							
							Element dishPrice = new Element("price");
							dishPrice.setText(""+dish.getPrice());
							
						dishElement.addContent(dishName);
						dishElement.addContent(dishPrice);
						
						command.addContent(dishElement);
					}
					
				delivery.addContent(command);
				
				Element price = new Element("price");
				price.setText(""+d.getPrice());
				delivery.addContent(price);
				
				Element taxes = new Element("taxes");
				taxes.setText(""+d.getTaxes());
				delivery.addContent(taxes);
				
				Element totalPrice = new Element("totalprice");
				totalPrice.setText(""+d.getTotalPrice());
				delivery.addContent(totalPrice);
				
			root.addContent(delivery);

		Dom.saveFile(dom, "bookOfDelivery.xml");
	}
}
